using KL.Core.Common.MyOptions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;

namespace KL.Standard.RabbitMQ
{
    
    /// <summary>
    /// 构建MQ链接工厂
    /// </summary>
    public class RabbitMQFactory<T>
    {
        private readonly ILogger<RabbitMQFactory<T>> _logger;
        private readonly RabbitMqVhost config;
        private readonly bool isEnabled;
        public RabbitMQFactory(IOptions<RabbitMqOptions> options,ILogger<RabbitMQFactory<T>> logger)
        {
            _logger = logger;
            var configMap = options.Value;
            var key = typeof(T).Name;
            isEnabled = configMap.Enabled;
            if (isEnabled)
                config = configMap.Vhosts.FirstOrDefault(x => x.Name == key);
        }
        private  ConnectionFactory factory;
        private  object lockObj = new object();
        /// <summary>
        /// 获取单个RabbitMQ连接
        /// </summary>
        /// <returns></returns>
        public  IConnection GetConnection()
        {
            if (!isEnabled)
                throw new Exception($" RabbitMq is not enabled from appSettings.json");
            var key = typeof(T).Name;
            if (config == null)
                throw new Exception($"Can not get RabbitMq config For {key} Instance");
            if (factory == null)
            {
                lock (lockObj)
                {
                    if (factory == null)
                    {
                        factory = new ConnectionFactory
                        {
                            HostName = this.config.IP,//ip
                            Port = this.config.PORT,//端口
                            UserName = this.config.USERID,//账号
                            Password = this.config.PWD,//密码
                            VirtualHost = this.config.VHOST //虚拟主机
                        };
                        _logger.LogInformation($"RabbitMQFactory  Instance: {factory.ToString()}");
                    }
                }
            }
            return factory.CreateConnection();
        }
    }
}